#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TCP队列优化演示脚本
展示多线程Queue架构的优势
"""

import sys
import os
import time
import threading
import logging
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from src.protocols.tcp.tcp_protocol import TCPClient

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

logger = logging.getLogger(__name__)

def demo_queue_optimization():
    """演示队列优化效果"""
    logger.info("=== TCP队列优化演示 ===")
    
    # 创建TCP客户端
    client = TCPClient(host='127.0.0.1', port=5000)
    
    logger.info("1. 创建TCP客户端实例")
    logger.info(f"   - 队列大小: {client.max_queue_size}")
    logger.info(f"   - 缓冲区大小: {client.max_buffer_size} bytes")
    logger.info(f"   - 背压延迟: {client.backpressure_delay} 秒")
    
    # 模拟数据接收
    logger.info("\n2. 模拟大量数据接收")
    
    # 生成测试消息
    test_messages = []
    for i in range(100):
        message = f"""<TRANSMIT>
<M>LD-600|SN123456</M>
<I>sample|{datetime.now().strftime('%Y%m%d%H%M%S')}|DEMO{i:03d}|DEMO{i:03d}|R001|01|QC</I>
<R>HbA1a|0.5|HbA1b|0.3|HbF|0.8|L-A1c|0.2|HbA1c|5.8|p3|0.1|HbA0|93.4|eAG|120.5</R>
</TRANSMIT>"""
        test_messages.append(message.encode('utf-8'))
    
    # 模拟快速接收数据
    logger.info("   开始快速接收数据...")
    start_time = time.time()
    
    for i, message in enumerate(test_messages):
        try:
            # 模拟网络接收延迟
            time.sleep(0.001)  # 1ms延迟
            
            # 将消息加入队列
            client.data_queue.put_nowait(message)
            
            if i % 20 == 0:
                queue_size = client.data_queue.qsize()
                logger.info(f"   已接收 {i} 条消息，队列大小: {queue_size}")
                
        except Exception as e:
            logger.warning(f"   队列已满，丢弃消息 {i}: {e}")
            break
    
    receive_time = time.time() - start_time
    logger.info(f"   接收完成，耗时: {receive_time:.3f} 秒")
    
    # 模拟数据处理
    logger.info("\n3. 模拟数据处理")
    processed_count = 0
    process_start = time.time()
    
    while not client.data_queue.empty():
        try:
            message_data = client.data_queue.get_nowait()
            # 模拟处理延迟
            time.sleep(0.005)  # 5ms处理延迟
            processed_count += 1
            
            if processed_count % 20 == 0:
                remaining = client.data_queue.qsize()
                logger.info(f"   已处理 {processed_count} 条消息，剩余: {remaining}")
                
        except Exception as e:
            logger.error(f"   处理消息错误: {e}")
            break
    
    process_time = time.time() - process_start
    logger.info(f"   处理完成，耗时: {process_time:.3f} 秒")
    
    # 性能分析
    logger.info("\n4. 性能分析")
    total_time = receive_time + process_time
    throughput = processed_count / total_time if total_time > 0 else 0
    
    logger.info(f"   总消息数: {processed_count}")
    logger.info(f"   总耗时: {total_time:.3f} 秒")
    logger.info(f"   吞吐量: {throughput:.2f} msg/s")
    logger.info(f"   接收时间占比: {receive_time/total_time*100:.1f}%")
    logger.info(f"   处理时间占比: {process_time/total_time*100:.1f}%")
    
    # 队列状态
    logger.info("\n5. 队列状态")
    status = client.get_queue_status()
    logger.info(f"   当前队列大小: {status['queue_size']}")
    logger.info(f"   最大队列大小: {status['max_queue_size']}")
    logger.info(f"   队列使用率: {status['queue_size']/status['max_queue_size']*100:.1f}%")
    
    logger.info("\n=== 演示完成 ===")

def demo_backpressure_control():
    """演示背压控制机制"""
    logger.info("\n=== 背压控制演示 ===")
    
    # 创建TCP客户端
    client = TCPClient(host='127.0.0.1', port=5000)
    
    logger.info("1. 设置较小的队列大小进行测试")
    client.max_queue_size = 10  # 设置小队列
    client.queue_warning_threshold = 8
    
    logger.info(f"   - 队列大小: {client.max_queue_size}")
    logger.info(f"   - 警告阈值: {client.queue_warning_threshold}")
    
    # 模拟快速数据流
    logger.info("\n2. 模拟快速数据流")
    
    def fast_data_producer():
        """快速数据生产者"""
        for i in range(50):
            message = f"<TRANSMIT>TEST{i:03d}</TRANSMIT>".encode('utf-8')
            
            # 检查队列大小，实施背压控制
            if client.data_queue.qsize() >= client.max_queue_size:
                logger.info(f"   队列已满 ({client.data_queue.qsize()}/{client.max_queue_size})，暂停接收")
                time.sleep(client.backpressure_delay)
                continue
            
            try:
                client.data_queue.put_nowait(message)
                logger.info(f"   发送消息 {i+1}")
            except Exception as e:
                logger.warning(f"   队列已满，丢弃消息 {i+1}")
                break
            
            time.sleep(0.01)  # 10ms间隔
    
    def slow_data_consumer():
        """慢速数据消费者"""
        processed = 0
        while processed < 50:
            try:
                message = client.data_queue.get(timeout=1.0)
                processed += 1
                logger.info(f"   处理消息 {processed}")
                time.sleep(0.1)  # 100ms处理延迟
            except Exception as e:
                break
    
    # 启动生产者和消费者线程
    producer_thread = threading.Thread(target=fast_data_producer)
    consumer_thread = threading.Thread(target=slow_data_consumer)
    
    producer_thread.start()
    consumer_thread.start()
    
    # 等待完成
    producer_thread.join()
    consumer_thread.join()
    
    logger.info("\n3. 背压控制效果")
    logger.info("   - 生产者速度: 100 msg/s")
    logger.info("   - 消费者速度: 10 msg/s")
    logger.info("   - 背压控制: 自动调节接收速度")
    logger.info("   - 结果: 防止内存溢出，保持系统稳定")
    
    logger.info("\n=== 背压控制演示完成 ===")

def main():
    """主函数"""
    logger.info("TCP队列优化演示程序启动")
    
    try:
        # 演示队列优化
        demo_queue_optimization()
        
        # 演示背压控制
        demo_backpressure_control()
        
        logger.info("\n演示程序完成！")
        logger.info("\n主要优势总结:")
        logger.info("1. 接收和处理分离，提高响应性")
        logger.info("2. 队列缓冲，防止数据丢失")
        logger.info("3. 背压控制，防止内存溢出")
        logger.info("4. 多线程并发，提高吞吐量")
        logger.info("5. 实时监控，便于调优")
        
    except Exception as e:
        logger.error(f"演示过程中出现错误: {e}")

if __name__ == "__main__":
    main()
